/**

	ascii.c
	=======
	
	ASCII character frequency analysis program.

**/ 


/**

	Includes
	--------
	
	- stdio.h	: getchar, printf
	- stdlib.h	: exit
	- stdint.h 	: uintX_t
	- signal.h 	: sigaction	
	
**/
 
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <signal.h>


/**

	Constant: ASCII_LEN
	-------------------
	
	Ascii array len
	
**/

#define ASCII_LEN		256




/**

	Global: totals
	--------------
	
	Ascii character array counter
	
**/

uint32_t totals[ASCII_LEN];


/**

	Global: count
	-------------
	
	Number of character encountered
	
**/

uint32_t count;


/**

	Function: void ascii_output(uint32_t* t, uint32_t n)
	----------------------------------------------------
	
	print ascii array `t` in terms of frequency (computed via `n`)
	
**/

void ascii_output()
{
	int i;
	float f;

	printf("float freq[] = { ");
	for(i=0; i<ASCII_LEN; i++)
	{
	  f = (totals[i]*100)/(float)count;
	  if (f==0.000) 
	    {
	      f = 0.0001;
	    }
	  printf("%0.3f%c",f,i==ASCII_LEN-1?'}':',');
	}
	printf(";\n");
	return;
}


/**

	Function: void handle_sigint(int signo)
	---------------------------------------
	
**/

void handle_sigint(int signo)
{
	
	ascii_output();
	exit(0);
}


/**

	Function: main
	--------------
	
	Entry point
	
**/


int main(int argc, char* argv[]) {

	int c;
	struct sigaction action,old_action;
	
	/* Setup */
	count = 0;
	
	/* Signal setup */
	action.sa_handler = handle_sigint;
	sigemptyset(&action.sa_mask);
	action.sa_flags = 0;
	if ( sigaction(SIGINT, &action, &old_action) < 0 )
	{
		exit(1);
	}

	/* Read input */
	while ((c = getchar()) != EOF) 
	{
		totals[c]++;
		count++;
	 }

	/* Output */
	ascii_output();

	return 0;
}
